#!/usr/bin/perl -w
# Given a fasta file of DNA sequences, prints the corresponding protein sequence
# for each DNA sequence.
use strict;
use warnings;

if (@ARGV != 1) {
  print "USAGE: $0 <fasta-formatted DNA sequence file>\n";
  exit;
}

# assumes the file contains DNA sequences
my ($fastaFile) = @ARGV; 

my %codonTable = (
 "AAA" => "K", "AAC" => "N", "AAG" => "K", "AAT" => "N",
 "ACA" => "T", "ACC" => "T", "ACG" => "T", "ACT" => "T",
 "AGA" => "R", "AGC" => "S", "AGG" => "R", "AGT" => "S",
 "ATA" => "I", "ATC" => "I", "ATG" => "M", "ATT" => "I",

 "CAA" => "Q", "CAC" => "H", "CAG" => "Q", "CAT" => "H",
 "CCA" => "P", "CCC" => "P", "CCG" => "P", "CCT" => "P",
 "CGA" => "R", "CGC" => "R", "CGG" => "R", "CGT" => "R",
 "CTA" => "L", "CTC" => "L", "CTG" => "L", "CTT" => "L",

 "GAA" => "E", "GAC" => "D", "GAG" => "E", "GAT" => "D",
 "GCA" => "A", "GCC" => "A", "GCG" => "A", "GCT" => "A",
 "GGA" => "G", "GGC" => "G", "GGG" => "G", "GGT" => "G",
 "GTA" => "V", "GTC" => "V", "GTG" => "V", "GTT" => "V",

 "TAA" => "X", "TAC" => "Y", "TAG" => "X", "TAT" => "Y",
 "TCA" => "S", "TCC" => "S", "TCG" => "S", "TCT" => "S",
 "TGA" => "X", "TGC" => "C", "TGG" => "W", "TGT" => "C",
 "TTA" => "L", "TTC" => "F", "TTG" => "L", "TTT" => "F" 
);

my %dnaFasta = getFastaFrom ($fastaFile);
my @labels = @{$dnaFasta{labels}};
my @dnaSequences = @{$dnaFasta{sequences}};
my @proteinSequences;

for(my $i=0; $i<@dnaSequences; $i++) {
  my $seq = $dnaSequences[$i];
  $seq =~ s/^.*?([ACGT]{3}.*?)[ACGT]{3}.*$/$1/;
  $seq = uc $seq; 
  my @codons = ( $seq =~ m/.{3}/g );
  my $protein = "";
  for (my $i=0; $i<@codons; $i++) {
    $protein .= $codonTable{$codons[$i]};
  }
  $proteinSequences[$i] = $protein; 
}

for (my $i=0; $i<@proteinSequences; $i++) {
  print $labels[$i], "\n", $proteinSequences[$i], "\n";
}

# including sequence labels
sub getFastaFrom {
  my ($fastafile) = @_;
  my (@labels, @sequences, %fasta);
  my $qty = 0;
  open (INPUT, $fastafile) or die "Can't open $fastafile: $!";

  while( my $line = <INPUT> ) {
    chomp $line;
    if( $line =~ /^\s*$/ ) {
      next;
    } elsif( $line =~ /^>/ ) {
      $qty++;
      $labels[$qty-1] = $line;
      $sequences[$qty-1] = "";  
    } else {
      # concatenate the line to the current sequence if it is not a label
      $line =~ s/\s//g;
      $sequences[$qty-1] .= $line;
    }
  }
  $fasta{labels} = \@labels;
  $fasta{sequences} = \@sequences;
  return %fasta;
}

